<template>
  <div class="expert-management">
    <n-card title="专家管理" :bordered="false" size="small" class="h-full shadow-sm rounded-8px">
      <template #header-extra>
        <n-space>
          <n-button type="primary" @click="handleAdd">
            <template #icon>
              <icon-park-outline-add-one />
            </template>
            新增专家
          </n-button>
        </n-space>
      </template>

      <!-- 搜索区域 -->
      <n-space class="pb-12px" justify="space-between">
        <n-space>
          <n-input
            v-model:value="searchParams.keyword"
            placeholder="搜索专家昵称"
            clearable
            class="w-200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <icon-park-outline-search class="text-16px" />
            </template>
          </n-input>
          <n-select
            v-model:value="searchParams.domain_id"
            placeholder="选择领域"
            clearable
            class="w-150px"
            :options="domainOptions"
          />
          <n-select
            v-model:value="searchParams.is_enabled"
            placeholder="启用状态"
            clearable
            class="w-120px"
            :options="statusOptions"
          />
          <n-button type="primary" @click="handleSearch">搜索</n-button>
          <n-button @click="handleReset">重置</n-button>
        </n-space>
      </n-space>

      <!-- 表格 -->
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :row-key="(row) => row.id"
        remote
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </n-card>

    <!-- 新增/编辑弹窗 -->
    <n-modal v-model:show="modalVisible" preset="dialog" :title="modalTitle" style="width: 90%; max-width: 1400px;">
      <n-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-placement="left"
        label-width="100px"
        class="pr-20px"
      >
        <n-grid :cols="24" :x-gap="20">
          <!-- 第一列：基本信息 (40%) -->
          <n-grid-item :span="10">
            <div class="column-container">
              <h3 class="column-title">基本信息</h3>
              <n-form-item label="所属领域" path="domain_id">
                <n-select
                  v-model:value="formData.domain_id"
                  placeholder="请选择领域"
                  :options="domainOptions"
                  clearable
                  :loading="!domainOptionsLoaded"
                  :disabled="!domainOptionsLoaded"
                  @update:value="handleDomainChange"
                  :render-label="(option) => option.label"
                  :render-tag="({ option }) => option.label"
                />
              </n-form-item>

              <n-form-item label="专家昵称" path="nickname">
                <n-input v-model:value="formData.nickname" placeholder="请输入专家昵称" />
              </n-form-item>
              
              <n-form-item label="专家简介" path="bio">
                <n-input
                  v-model:value="formData.bio"
                  type="textarea"
                  placeholder="请输入专家简介"
                  :rows="4"
                />
              </n-form-item>
              
              <n-form-item label="欢迎语" path="welcome_message">
                <n-input
                  v-model:value="formData.welcome_message"
                  type="textarea"
                  placeholder="请输入专家欢迎语"
                  :rows="3"
                />
              </n-form-item>
              
              <n-form-item label="头像图片" path="avatar_url">
                <n-upload
                  :default-file-list="avatarFileList"
                  :max="1"
                  list-type="image-card"
                  accept="image/*"
                  :custom-request="handleAvatarUpload"
                  @change="handleAvatarChange"
                  @remove="handleAvatarRemove"
                >
                  点击上传头像
                </n-upload>
              </n-form-item>

              <n-form-item label="展示大图" path="display_images">
                <n-upload
                  :default-file-list="displayImagesList"
                  :max="5"
                  list-type="image-card"
                  accept="image/*"
                  multiple
                  :custom-request="handleDisplayImagesUpload"
                  @change="handleDisplayImagesChange"
                  @remove="handleDisplayImageRemove"
                >
                  点击上传展示图片（最多5张）
                </n-upload>
              </n-form-item>
              
              <n-grid :cols="2" :x-gap="20">
                <n-grid-item>
                  <n-form-item label="排序权重" path="sort_order">
                    <n-input-number v-model:value="formData.sort_order" :min="0" placeholder="排序权重" />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item>
                  <n-form-item label="启用状态" path="is_enabled">
                    <n-switch v-model:value="formData.is_enabled" />
                  </n-form-item>
                </n-grid-item>
              </n-grid>
              
              <n-form-item label="外部专家ID" path="external_expert_id">
                <n-space vertical class="w-full">
                  <n-input-group>
                    <n-input
                      v-model:value="formData.external_expert_id"
                      placeholder="请输入外部专家ID或点击右侧按钮绑定"
                      clearable
                      class="flex-1"
                    />
                    <n-button
                      type="primary"
                      @click="openExpertSelectionModal"
                      :loading="externalExpertLoading"
                    >
                      <template #icon>
                        <icon-park-outline-link />
                      </template>
                      绑定外部ID
                    </n-button>
                  </n-input-group>
                  <n-text depth="3" style="font-size: 12px;">
                    从外部知识库系统获取专家列表并进行绑定，或直接输入已知的外部专家ID
                  </n-text>
                </n-space>
              </n-form-item>
            </div>
          </n-grid-item>

          <!-- 第二列：经典案例 (40%) -->
          <n-grid-item :span="10">
            <div class="column-container">
              <h3 class="column-title">经典案例</h3>
              <div class="w-full cases-container">
                <div class="cases-scroll-area">
                  <div v-for="(caseItem, index) in formData.classic_cases" :key="index" class="mb-12px">
                    <n-card size="small" :title="`案例 ${index + 1}`">
                      <template #header-extra>
                        <n-space>
                          <n-button
                            size="small"
                            type="primary"
                            :disabled="index === 0"
                            @click="moveCaseUp(index)"
                            title="上移"
                          >
                            <template #icon>
                              <icon-park-outline-up />
                            </template>
                          </n-button>
                          <n-button
                            size="small"
                            type="primary"
                            :disabled="index === formData.classic_cases.length - 1"
                            @click="moveCaseDown(index)"
                            title="下移"
                          >
                            <template #icon>
                              <icon-park-outline-down />
                            </template>
                          </n-button>
                          <n-button size="small" type="error" @click="removeCase(index)">删除</n-button>
                        </n-space>
                      </template>
                      <n-form-item>
                        <n-input
                          v-model:value="caseItem.question"
                          placeholder="请输入问题"
                          type="textarea"
                          :rows="2"
                        />
                      </n-form-item>
                      <n-form-item>
                        <n-input
                          v-model:value="caseItem.answer"
                          placeholder="请输入答案"
                          type="textarea"
                          :rows="3"
                        />
                      </n-form-item>
                    </n-card>
                  </div>
                </div>
                <n-button @click="addCase" dashed class="w-full mt-3">
                  <template #icon>
                    <icon-park-outline-add-one />
                  </template>
                  添加案例
                </n-button>
              </div>
            </div>
          </n-grid-item>

          <!-- 第三列：定价配置 (20%) -->
          <n-grid-item :span="4">
            <div class="column-container">
              <h3 class="column-title">定价配置</h3>
              <div class="w-full pricing-container">
                <div v-for="(pricingItem, index) in formData.pricing" :key="index" class="pricing-item">
                  <div class="pricing-header">
                    <span class="pricing-title">定价 {{ index + 1 }}</span>
                    <n-button size="small" type="error" @click="removePricing(index)">删除</n-button>
                  </div>
                  <div class="pricing-field">
                    <label class="pricing-label">购买数量</label>
                    <n-input-number
                      v-model:value="pricingItem.quantity"
                      placeholder="请输入数量"
                      :min="1"
                      :max="1000"
                      :precision="0"
                      class="w-full"
                    />
                  </div>
                  <div class="pricing-field">
                    <label class="pricing-label">价格（元）</label>
                    <n-input-number
                      v-model:value="pricingItem.price"
                      placeholder="请输入价格"
                      :min="0.01"
                      :max="9999.99"
                      :precision="2"
                      class="w-full"
                    />
                  </div>
                </div>
                <n-button @click="addPricing" dashed class="w-full mt-3">
                  <template #icon>
                    <icon-park-outline-add-one />
                  </template>
                  添加定价阶梯
                </n-button>
              </div>
            </div>
          </n-grid-item>
        </n-grid>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="modalVisible = false">取消</n-button>
          <n-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 高危删除确认弹窗 -->
    <DangerousActionConfirm
      v-model:visible="deleteConfirmVisible"
      :title="`删除专家: ${currentDeleteItem?.nickname || ''}`"
      :description="`您即将删除专家「${currentDeleteItem?.nickname || ''}」，此操作将删除该专家的所有信息和相关数据。`"
      :item-info="deleteItemInfo"
      :risks="deleteRisks"
      @confirm="handleConfirmDelete"
      @cancel="handleCancelDelete"
      ref="deleteConfirmRef"
    />

    <!-- 外部专家选择弹窗 -->
    <n-modal v-model:show="expertSelectionModalVisible" preset="dialog" title="选择外部专家" style="min-width: 500px;">
      <template #header>
        <div class="flex items-center justify-between w-full">
          <div>选择外部专家</div>
          <n-space v-if="!externalExpertLoading">
            <n-text depth="3">找到 {{ filteredExternalExperts.length }} 位专家</n-text>
          </n-space>
        </div>
      </template>
      
      <div class="pb-4">
        <n-input
          v-model:value="expertSearchKeyword"
          placeholder="搜索专家名称或ID"
          clearable
          :disabled="externalExpertLoading"
        >
          <template #prefix>
            <icon-park-outline-search />
          </template>
        </n-input>
      </div>

      <div class="external-experts-modal-content">
        <n-spin :show="externalExpertLoading">
          <n-empty v-if="filteredExternalExperts.length === 0 && !externalExpertLoading" description="暂无匹配专家" />
          <n-list v-else hoverable clickable>
            <n-list-item
              v-for="expert in filteredExternalExperts"
              :key="expert.value"
              @click="selectExternalExpert(expert)"
              :class="{ 'expert-selected': expert.value === currentSelectedExpertId }"
            >
              <n-thing>
                <template #header>
                  <n-text>{{ expert.label.split('(')[0].trim() }}</n-text>
                </template>
                <template #description>
                  <n-tag size="small" type="info">ID: {{ expert.value }}</n-tag>
                </template>
              </n-thing>
            </n-list-item>
          </n-list>
        </n-spin>
      </div>
      
      <template #action>
        <n-space justify="space-between" style="width: 100%">
          <n-button @click="loadExternalExperts" :disabled="externalExpertLoading">
            <template #icon>
              <icon-park-outline-refresh />
            </template>
            刷新列表
          </n-button>
          <n-button @click="expertSelectionModalVisible = false">关闭</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, h, nextTick } from 'vue'
import type { DataTableColumns, UploadFileInfo } from 'naive-ui'
import { NButton, NTag, NSpace, NAvatar, NPopover, NQrCode, useMessage, useDialog } from 'naive-ui'
import { expertApi, domainApi, serviceIntegrationApi } from '@/service/api/bizhi'
import { filterApiParams, filterFormData } from '@/utils/api'
import { formatTime } from '@/utils/time'
import { generateImageUrl, preloadImageUrlTemplate } from '@/utils/image'
import DangerousActionConfirm from '@/components/DangerousActionConfirm.vue'

const message = useMessage()
const dialog = useDialog()

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const modalVisible = ref(false)
const tableData = ref([])
const formRef = ref()
const domainOptions = ref([])
const domainOptionsLoaded = ref(false)
const avatarFileList = ref<UploadFileInfo[]>([])
const displayImagesList = ref<UploadFileInfo[]>([])
const showDebugInfo = ref(false) // 开发时可以设置为 true

// 专家页面URL模板
const expertPageUrlTemplate = ref('')

// 外部专家相关
const externalExpertLoading = ref(false)
const externalExpertOptions = ref([])

// 删除确认相关
const deleteConfirmVisible = ref(false)
const deleteConfirmRef = ref()
const currentDeleteItem = ref(null)

// 搜索参数
const searchParams = reactive({
  keyword: '',
  domain_id: null,
  is_enabled: null,
  page: 1,
  limit: 20
})

// 表单数据
const formData = reactive({
  id: null,
  domain_id: null,
  nickname: '',
  bio: '',
  welcome_message: '',
  avatar_url: '',
  display_images: [],
  classic_cases: [],
  pricing: [],
  sort_order: 0,
  is_enabled: true,
  external_expert_id: ''
})

// 删除确认相关计算属性
const deleteItemInfo = computed(() => {
  if (!currentDeleteItem.value) return {}
  const item = currentDeleteItem.value
  return {
    'ID': item.id,
    '专家昵称': item.nickname,
    '真实姓名': item.real_name || '-',
    '所属领域': item.domain_name || '-',
    '专业描述': item.professional_description || '-',
    '启用状态': item.is_enabled ? '启用' : '禁用',
    '排序权重': item.sort_order || 0,
    '创建时间': formatTime(item.created_at)
  }
})

const deleteRisks = computed(() => {
  return [
    '删除后该专家信息将无法恢复',
    '该专家的所有经典案例将被删除',
    '用户将无法再向该专家提问',
    '所有相关的问答记录将失去专家关联',
    '专家的头像和展示图片将被删除',
    '相关的统计数据将受到影响'
  ]
})

// 状态选项
const statusOptions = [
  { label: '启用', value: true },
  { label: '禁用', value: false }
]

// 表单验证规则
const formRules = {
  domain_id: [
    {
      required: true,
      message: '请选择所属领域',
      trigger: 'blur',
      type: 'number'
    }
  ],
  nickname: [
    { required: true, message: '请输入专家昵称', trigger: 'blur' },
    { max: 100, message: '专家昵称不能超过100个字符', trigger: 'blur' }
  ]
}

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 20,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100]
})

// 弹窗标题
const modalTitle = computed(() => {
  return formData.id ? '编辑专家' : '新增专家'
})

// 表格列配置
const columns: DataTableColumns = [
  { title: 'ID', key: 'id', width: 80 },
  {
    title: '头像',
    key: 'avatar_url',
    width: 80,
    render: (row: any) => {
      // 如果有头像URL，显示头像；否则显示昵称首字母
      if (row.avatar_url) {
        return h(NAvatar, {
          size: 40,
          src: row.avatar_url,
          fallbackSrc: '/default-avatar.png'
        })
      } else {
        // 根据专家ID生成不同的背景颜色
        const colors = ['#1890ff', '#52c41a', '#fa8c16', '#eb2f96', '#722ed1', '#13c2c2', '#f5222d']
        const backgroundColor = colors[row.id % colors.length]

        return h(NAvatar, {
          size: 40,
          style: { backgroundColor, color: 'white' }
        }, {
          default: () => row.nickname ? row.nickname.charAt(0) : '?'
        })
      }
    }
  },
  { title: '昵称', key: 'nickname', width: 120 },
  { title: '所属领域', key: 'domain.name', width: 120 },
  { title: '简介', key: 'bio', ellipsis: { tooltip: true } },
  {
    title: '启用状态',
    key: 'is_enabled',
    width: 100,
    render: (row: any) => {
      return h(NTag, {
        type: row.is_enabled ? 'success' : 'error'
      }, {
        default: () => row.is_enabled ? '启用' : '禁用'
      })
    }
  },
  { title: '排序权重', key: 'sort_order', width: 100 },
  {
    title: '定价',
    key: 'pricing',
    width: 120,
    render: (row: any) => {
      if (!row.pricing || !Array.isArray(row.pricing) || row.pricing.length === 0) {
        return '未设置'
      }
      const minPrice = Math.min(...row.pricing.map((p: any) => p.price))
      return `¥${minPrice}起`
    }
  },
  {
    title: '创建时间',
    key: 'created_at',
    width: 180,
    render: (row: any) => formatTime(row.created_at)
  },
  {
    title: '操作',
    key: 'actions',
    width: 280,
    render: (row: any) => {
      return h(NSpace, {}, {
        default: () => [
          h(NButton, {
            size: 'small',
            type: 'primary',
            onClick: () => handleEdit(row)
          }, { default: () => '编辑' }),
          h(NPopover, {
            trigger: 'hover',
            placement: 'top'
          }, {
            trigger: () => h(NButton, {
              size: 'small',
              type: 'info',
              onClick: () => handleOpenExpertPage(row)
            }, { default: () => '专家页面' }),
            default: () => h('div', { style: 'text-align: center;' }, [
              h('div', { style: 'margin-bottom: 8px; font-size: 12px; color: #666;' }, '专家详情页面'),
              h(NQrCode, {
                value: getExpertPageUrl(row.id),
                size: 120,
                padding: 8
              })
            ])
          }),
          h(NButton, {
            size: 'small',
            type: 'error',
            onClick: () => handleDelete(row)
          }, { default: () => '删除' })
        ]
      })
    }
  }
]

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    domain_id: null,
    nickname: '',
    bio: '',
    welcome_message: '',
    avatar_url: '',
    display_images: [],
    classic_cases: [],
    pricing: [],
    sort_order: 0,
    is_enabled: true,
    external_expert_id: ''
  })
}

// 处理领域选择变化
const handleDomainChange = (value: number | null) => {
  console.log('领域选择变化:', value)
  formData.domain_id = value
}

// 获取领域选项
const fetchDomainOptions = async () => {
  try {
    domainOptionsLoaded.value = false
    // 管理后台应该显示所有领域，不仅仅是启用的领域
    const response = await domainApi.getDomainList({})

    // 确保数据格式正确
    const options = response.data.list.map((domain: any) => ({
      label: domain.name,
      value: Number(domain.id) // 确保 value 是数字类型
    }))

    domainOptions.value = options
    domainOptionsLoaded.value = true

    console.log('领域选项加载完成:', options)
  } catch (error) {
    console.error('获取领域列表失败:', error)
    message.error('获取领域列表失败')
    domainOptions.value = []
    domainOptionsLoaded.value = false
  }
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const response = await expertApi.getExpertList(filterApiParams(searchParams))
    tableData.value = response.data.list || []
    pagination.itemCount = response.data.pagination?.total || 0
  } catch (error) {
    console.error('获取专家数据失败:', error)
    message.error('获取数据失败')
    tableData.value = []
    pagination.itemCount = 0
  } finally {
    loading.value = false
  }
}

// 添加案例
const addCase = () => {
  formData.classic_cases.push({
    question: '',
    answer: ''
  })
}

// 删除案例
const removeCase = (index: number) => {
  formData.classic_cases.splice(index, 1)
}

// 添加定价阶梯
const addPricing = () => {
  formData.pricing.push({
    quantity: 1,
    price: 0
  })
}

// 删除定价阶梯
const removePricing = (index: number) => {
  formData.pricing.splice(index, 1)
}

// 上移案例
const moveCaseUp = (index: number) => {
  if (index > 0) {
    const cases = formData.classic_cases
    const temp = cases[index]
    cases[index] = cases[index - 1]
    cases[index - 1] = temp
  }
}

// 下移案例
const moveCaseDown = (index: number) => {
  if (index < formData.classic_cases.length - 1) {
    const cases = formData.classic_cases
    const temp = cases[index]
    cases[index] = cases[index + 1]
    cases[index + 1] = temp
  }
}

// 头像上传变化
const handleAvatarChange = (options: { fileList: UploadFileInfo[] }) => {
  avatarFileList.value = options.fileList
  if (options.fileList.length > 0) {
    formData.avatar_url = options.fileList[0].url || ''
  } else {
    formData.avatar_url = ''
  }
}

// 展示图片上传变化
const handleDisplayImagesChange = (options: { fileList: UploadFileInfo[] }) => {
  displayImagesList.value = options.fileList
  formData.display_images = options.fileList.map(file => file.url || '')
}

// 头像自定义上传
const handleAvatarUpload = async ({ file, onFinish, onError, onProgress }: any) => {
  try {
    if (!formData.id) {
      message.warning('请先保存专家基本信息后再上传头像')
      onError()
      return
    }

    const formDataUpload = new FormData()
    formDataUpload.append('avatar', file.file)

    onProgress({ percent: 50 })

    const response = await expertApi.uploadAvatar(formData.id, formDataUpload) as any

    if (response.data && response.data.avatar_url) {
      // 更新表单数据
      formData.avatar_url = response.data.avatar_url

      // 更新文件列表
      file.url = response.data.avatar_url
      file.status = 'finished'

      onProgress({ percent: 100 })
      onFinish()
      message.success('头像上传成功')
    } else {
      throw new Error('上传响应格式错误')
    }
  } catch (error: any) {
    console.error('头像上传失败:', error)
    const errorMessage = error?.response?.data?.message || error?.message || '头像上传失败'
    message.error(errorMessage)
    onError()
  }
}

// 展示图片自定义上传
const handleDisplayImagesUpload = async ({ file, onFinish, onError, onProgress }: any) => {
  try {
    if (!formData.id) {
      message.warning('请先保存专家基本信息后再上传展示图片')
      onError()
      return
    }

    const formDataUpload = new FormData()
    formDataUpload.append('display_images', file.file)

    onProgress({ percent: 50 })

    const response = await expertApi.uploadDisplayImages(formData.id, formDataUpload) as any

    if (response.data && response.data.display_images) {
      // 更新表单数据 - 合并新上传的图片
      const newImages = response.data.display_images
      const existingImages = formData.display_images || []
      formData.display_images = [...existingImages, ...newImages]

      // 更新文件列表
      file.url = newImages[0] // 取第一个新上传的图片URL
      file.status = 'finished'

      onProgress({ percent: 100 })
      onFinish()
      message.success('展示图片上传成功')
    } else {
      throw new Error('上传响应格式错误')
    }
  } catch (error: any) {
    console.error('展示图片上传失败:', error)
    const errorMessage = error?.response?.data?.message || error?.message || '展示图片上传失败'
    message.error(errorMessage)
    onError()
  }
}

// 头像移除处理
const handleAvatarRemove = () => {
  formData.avatar_url = ''
}

// 展示图片移除处理
const handleDisplayImageRemove = ({ file }: any) => {
  const index = displayImagesList.value.findIndex(item => item.id === file.id)
  if (index > -1) {
    formData.display_images.splice(index, 1)
  }
}



// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchParams, {
    keyword: '',
    domain_id: null,
    is_enabled: null,
    page: 1,
    limit: 20
  })
  fetchData()
}

// 分页变化
const handlePageChange = (page: number) => {
  pagination.page = page
  searchParams.page = page
  fetchData()
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.page = 1
  searchParams.limit = pageSize
  searchParams.page = 1
  fetchData()
}

// 新增
const handleAdd = () => {
  try {
    console.log('点击新增专家')
    resetFormData()
    avatarFileList.value = []
    displayImagesList.value = []
    modalVisible.value = true
    console.log('弹窗应该已打开:', modalVisible.value)
  } catch (error) {
    console.error('新增专家时出错:', error)
    message.error('打开新增弹窗失败')
  }
}

// 编辑
const handleEdit = async (row: any) => {
  try {
    console.log('开始编辑专家:', row)

    // 确保 domainOptions 已加载
    if (!domainOptionsLoaded.value) {
      console.log('领域选项未加载，开始加载...')
      await fetchDomainOptions()
    }

    if (domainOptions.value.length === 0) {
      message.warning('无法加载领域数据，请稍后再试')
      return
    }

    // 重置表单数据
    resetFormData()

    // 设置表单数据
    Object.assign(formData, {
      id: row.id,
      domain_id: row.domain_id ? Number(row.domain_id) : null,
      nickname: row.nickname || '',
      bio: row.bio || '',
      welcome_message: row.welcome_message || '',
      avatar_url: row.avatar_url || '',
      display_images: row.display_images || [],
      classic_cases: row.classic_cases || [],
      pricing: row.pricing || [],
      sort_order: row.sort_order || 0,
      is_enabled: row.is_enabled !== undefined ? row.is_enabled : true,
      external_expert_id: row.external_expert_id || ''
    })

    console.log('设置后的表单数据:', formData)

    // 设置文件列表
    avatarFileList.value = row.avatar_url ? [{
      id: 'avatar',
      name: 'avatar.jpg',
      status: 'finished',
      url: row.avatar_url
    }] : []

    displayImagesList.value = row.display_images?.map((url: string, index: number) => ({
      id: `display_${index}`,
      name: `display_${index}.jpg`,
      status: 'finished',
      url
    })) || []

    // 打开弹窗
    modalVisible.value = true

    // 延迟清除表单验证，确保DOM更新完成
    setTimeout(() => {
      formRef.value?.restoreValidation()
      console.log('验证状态已清除')

      // 强制触发选择器更新
      const currentDomainId = formData.domain_id
      formData.domain_id = null
      setTimeout(() => {
        formData.domain_id = currentDomainId
        console.log('强制更新 domain_id:', currentDomainId)
      }, 50)
    }, 200)
  } catch (error) {
    console.error('编辑专家时出错:', error)
    message.error('打开编辑弹窗失败')
  }
}

// 删除 - 显示高危确认弹窗
const handleDelete = (row: any) => {
  currentDeleteItem.value = row
  deleteConfirmVisible.value = true
}

// 确认删除
const handleConfirmDelete = async (password: string) => {
  try {
    // 这里应该调用API验证管理员密码
    // 暂时模拟验证逻辑
    if (password.length < 6) {
      message.error('密码长度不能少于6位')
      return
    }

    // 执行删除操作
    if (!currentDeleteItem.value) {
      message.error('删除项目不存在')
      return
    }

    const result = await expertApi.deleteExpert(currentDeleteItem.value.id, password)

    // 检查Alova返回的结果
    if (result && !result.isSuccess) {
      // 这是业务逻辑错误（如API返回code: 400）
      let errorMessage = result.message || '删除失败，请重试'

      console.error('删除业务逻辑错误:', result)
      message.error(errorMessage)
      return // 不关闭弹窗，让用户可以重试
    }

    // 只有真正成功才会执行到这里
    message.success('删除成功')
    deleteConfirmVisible.value = false
    currentDeleteItem.value = null
    fetchData()
  } catch (error) {
    console.error('删除网络异常:', error)

    // 这里只处理真正的网络异常（网络错误、超时等）
    let errorMessage = '网络错误，请检查网络连接后重试'

    if (error?.message) {
      errorMessage = error.message
    }

    message.error(errorMessage)

    // 网络异常时不关闭弹窗，让用户可以重试
  } finally {
    deleteConfirmRef.value?.setLoading(false)
  }
}

// 取消删除
const handleCancelDelete = () => {
  currentDeleteItem.value = null
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()

    submitLoading.value = true

    // 过滤掉null值的表单数据，但保留图片相关字段用于后续处理
    const filteredData = filterFormData(formData)

    let expertId = formData.id
    let isNewExpert = false

    if (formData.id) {
      // 更新现有专家
      await expertApi.updateExpert(formData.id, filteredData)
    } else {
      // 创建新专家
      const createResponse = await expertApi.createExpert(filteredData) as any
      expertId = createResponse.data?.id
      isNewExpert = true

      if (!expertId) {
        throw new Error('创建专家失败，未获取到专家ID')
      }

      // 更新表单数据中的ID，以便后续上传图片
      formData.id = expertId
    }

    // 处理图片上传（新建和编辑都需要）
    if (expertId) {
      await handleImageUploads(expertId, isNewExpert)
    }

    message.success(isNewExpert ? '创建成功' : '更新成功')
    modalVisible.value = false
    fetchData()
  } catch (error: any) {
    console.error('提交失败:', error)
    const errorMessage = error?.response?.data?.message || error?.message || '操作失败，请重试'
    message.error(errorMessage)
  } finally {
    submitLoading.value = false
  }
}

// 处理图片上传
const handleImageUploads = async (expertId: number, isNewExpert: boolean) => {
  try {
    // 处理头像上传
    const avatarFile = avatarFileList.value.find(file => file.file && file.status !== 'finished')
    if (avatarFile && avatarFile.file) {
      const avatarFormData = new FormData()
      avatarFormData.append('avatar', avatarFile.file)

      const avatarResponse = await expertApi.uploadAvatar(expertId, avatarFormData) as any
      if (avatarResponse.data?.avatar_url) {
        formData.avatar_url = avatarResponse.data.avatar_url
      }
    }

    // 处理展示图片上传
    const newDisplayImages = displayImagesList.value.filter(file => file.file && file.status !== 'finished')
    if (newDisplayImages.length > 0) {
      for (const imageFile of newDisplayImages) {
        if (imageFile.file) {
          const imageFormData = new FormData()
          imageFormData.append('display_images', imageFile.file)

          const imageResponse = await expertApi.uploadDisplayImages(expertId, imageFormData) as any
          if (imageResponse.data?.display_images) {
            // 更新文件状态
            imageFile.status = 'finished'
            imageFile.url = imageResponse.data.display_images[0]
          }
        }
      }
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    // 图片上传失败不影响专家信息保存，只显示警告
    message.warning('专家信息保存成功，但部分图片上传失败，请重新编辑上传')
  }
}

// 加载外部专家列表
const loadExternalExperts = async () => {
  try {
    externalExpertLoading.value = true

    // 使用新的SystemK专用API调用方法
    const result = await serviceIntegrationApi.callSystemKApi('getExpertList', {})

    if (result.data && Array.isArray(result.data)) {
      externalExpertOptions.value = result.data.map(expert => {
        // 构造显示名称: name-nickname
        let displayName = expert.name || ''
        if (expert.nickname) {
          displayName = displayName ? `${displayName}「${expert.nickname}」` : expert.nickname
        }
        
        // 如果没有name和nickname，则显示未知专家
        if (!displayName) {
          displayName = '未知专家'
        }
        
        return {
          label: `${displayName} (${expert._id || expert.id})`,
          value: expert._id || expert.id // 优先使用_id字段，如果不存在则使用id
        }
      })
      message.success(`成功获取 ${externalExpertOptions.value.length} 个外部专家`)
    } else {
      externalExpertOptions.value = []
      message.warning('外部系统返回的专家列表为空')
    }
  } catch (error) {
    console.error('获取外部专家列表失败:', error)
    externalExpertOptions.value = []

    const errorMessage = error?.response?.data?.message || error?.message || '获取外部专家列表失败'

    if (error?.response?.status === 404) {
      message.warning('服务联动配置不存在，请先在系统设置中配置')
    } else {
      message.error(errorMessage)
    }
  } finally {
    externalExpertLoading.value = false
  }
}

// 外部专家选择相关
const expertSelectionModalVisible = ref(false)
const expertSearchKeyword = ref('')
const currentSelectedExpertId = ref('')
const filteredExternalExperts = computed(() => {
  if (!expertSearchKeyword.value) {
    return externalExpertOptions.value
  }
  
  const keyword = expertSearchKeyword.value.toLowerCase()
  return externalExpertOptions.value.filter(expert => {
    const label = expert.label.toLowerCase()
    const value = expert.value.toLowerCase()
    return label.includes(keyword) || value.includes(keyword)
  })
})

// 打开专家选择弹窗
const openExpertSelectionModal = async () => {
  expertSelectionModalVisible.value = true
  expertSearchKeyword.value = ''
  
  // 如果还没有加载过专家列表，则自动加载
  if (externalExpertOptions.value.length === 0) {
    await loadExternalExperts()
  }
  
  // 如果文本框已有外部专家ID，则设置为当前选中项
  if (formData.external_expert_id) {
    currentSelectedExpertId.value = formData.external_expert_id
    
    // 如果存在该专家，则自动滚动到该专家位置
    nextTick(() => {
      const selectedElement = document.querySelector('.expert-selected')
      if (selectedElement) {
        selectedElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
      }
    })
  } else {
    currentSelectedExpertId.value = ''
  }
}

// 选择外部专家
const selectExternalExpert = (expert: { label: string, value: string }) => {
  formData.external_expert_id = expert.value
  currentSelectedExpertId.value = expert.value
  message.success(`已选择专家: ${expert.label}`)
  expertSelectionModalVisible.value = false
}

// 获取专家页面URL模板
const loadExpertPageUrlTemplate = async () => {
  try {
    const result = await serviceIntegrationApi.getServiceConfig('system_a') as any
    const config = result.data
    if (config?.api_config?.expertDetailPage?.urlTemplate) {
      expertPageUrlTemplate.value = config.api_config.expertDetailPage.urlTemplate
    }
  } catch (error) {
    console.error('获取专家页面URL模板失败:', error)
  }
}

// 生成专家页面URL
const getExpertPageUrl = (expertId: number) => {
  if (!expertPageUrlTemplate.value) {
    return '#'
  }
  return expertPageUrlTemplate.value.replace('{expert_id}', expertId.toString())
}

// 打开专家页面
const handleOpenExpertPage = (row: any) => {
  const url = getExpertPageUrl(row.id)
  if (url === '#') {
    message.warning('专家页面URL模板未配置，请先在服务联动配置中设置')
    return
  }
  window.open(url, '_blank')
}

onMounted(() => {
  fetchDomainOptions()
  fetchData()
  loadExpertPageUrlTemplate()
  preloadImageUrlTemplate() // 预加载图片URL模板
})
</script>

<style scoped>
.expert-management {
  height: 100%;
}

.cases-container {
  display: flex;
  flex-direction: column;
}

.cases-scroll-area {
  max-height: 670px;
  overflow-y: auto;
  padding-right: 8px;
}

.external-experts-container {
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 8px;
  margin-top: 8px;
  max-height: 200px;
  overflow-y: auto;
}

.external-experts-header {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 8px;
}

.external-experts-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.expert-tag {
  cursor: pointer;
  transition: all 0.2s;
}

.expert-tag:hover {
  background-color:rgba(11, 216, 79, 0.12);
  transform: translateY(-2px);
}

.external-experts-modal-content {
  max-height: 400px;
  overflow-y: auto;
  margin: 0 -16px;
  padding: 0 16px;
}

.expert-selected {
  background-color: rgba(0, 128, 255, 0.1);
  border-left: 3px solid #0080ff;
}

/* 三列布局样式 */
.column-container {
  height: 100%;
  position: relative;
}

.column-container:not(:last-child)::after {
  content: '';
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 1px;
  background-color: #e0e0e6;
}

.column-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 定价项样式 */
.pricing-item {
  margin-bottom: 16px;
  padding: 12px;
  border: 1px solid #e0e0e6;
  border-radius: 6px;
  background-color: #fafafa;
}

.pricing-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.pricing-title {
  font-weight: 500;
  color: #333;
}

/* 定价字段样式 */
.pricing-field {
  margin-bottom: 12px;
}

.pricing-label {
  display: block;
  margin-bottom: 4px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}
</style>
